package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.rocksdb.WALRecoveryMode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {


  /*
  *
  *
  * 添加任务
  * */
    @Override
    public long addTask(Task task) {
      //添加任务到数据库
      boolean success= addTaskToDb(task);

        //添加任务到redis缓存
  if(success){
      addTaskTOCache(task);
  }

        return 0;
    }


   /*
   *
   * 取消任务
   *
   * */
    @Override
    public boolean deleteTask(Long taskId) {
        //删除任务，更新任务日志
   Task task=updateBb(taskId);

        //删除redis的数据
        if(task!=null){
            removeCache(task);
        }
        return false;
    }


    /*
    *
    * 拉去任务
    * */
    @Override
    public Task pull(int Type, int Priority) {
        Task task=null;
        String key = Type+"_"+Priority;
       //从redis拉去数据
        String s = cacheService.lRightPop(key);
        if(StringUtils.isNoneBlank(s)){
             task = JSON.parseObject(s, Task.class);
        }
      //修改数据库状态、

        return task;
    }

    /*
    *
    * 删除redis中的数据
    * */
    private void removeCache(Task task) {
        String key = task.getTaskType()+"_"+task.getPriority();
        if(task.getExecuteTime()<=System.currentTimeMillis()){
          cacheService.lRemove(key,0,JSON.toJSONString(task));
        }else{
            cacheService.zRemove(key,JSON.toJSONString(task));
        }
    }

    /*
    * 更新任务
    * */
    private Task updateBb(Long taskId) {
        //删除任务表
        taskinfoMapper.deleteById(taskId);

        //更新任务日志
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);

        Task task=new Task();
        BeanUtils.copyProperties(taskinfoLogs, task);
        return task;
    }

    @Autowired
    private CacheService cacheService;
    /*
    *
    * 把任务添加到redis缓存
    * */
    private void addTaskTOCache(Task task) {
         String key = task.getTaskType()+"_"+task.getPriority();

         //获取5分钟之后的执行时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextScheduleTime= calendar.getTimeInMillis();
        //如果任务执行时间小于当前时间，存入List
          if(task.getExecuteTime()<=System.currentTimeMillis()){
              cacheService.lLeftPush(key, JSON.toJSONString(task));
          } else if (task.getExecuteTime()<=nextScheduleTime) {
              //如果当前任务大于当前时间&&小于预计时间（5分钟）存入zset
              cacheService.zAdd(key,JSON.toJSONString(task),task.getExecuteTime());
              
          }


    }

    //任务表
    @Autowired
    private TaskinfoMapper taskinfoMapper;

    //任务日志表
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    /* //添加任务到数据库*/
    private boolean addTaskToDb(Task task) {

      boolean flag=false;
        try{
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(0);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag=true;
        }catch (Exception e){
            e.printStackTrace();

        }
        return flag;

    }

    @Scheduled(cron = "0*/1 * * * * ?")
    public void  refresh(){

      //获取所有未来数据的集合
        Set<String> futureKeys = cacheService.scan("*");
        for (String futureKey : futureKeys) {
           //获取当前数据的key


            cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());



        }

    }
    /*
    *
    * 数据库任务同步到redis缓存
    * */
    @Scheduled(cron="0 */5 * * * ?")
    public void reloadData(){

        //清理缓存中的数据
        cleancache();
        //查询数据库中符合条件的任务，小于未来5分钟
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, System.currentTimeMillis() + 5 * 60 * 1000));

        //把任务集成到redis缓存中
        if(taskinfoList!=null&&taskinfoList.size()>0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskTOCache(task);
            }
        }
        log.info("同步任务到redis缓存完成");
    }
    public void  cleancache(){
        Set<String> topickeys = cacheService.scan("*");
        cacheService.delete(topickeys);


    }
}
